package com.jiangyifen.robot.sdkserver;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.GlobalEventExecutor;

@Component
public final class RobotSdkServer {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	
	@Value("${robot_sdk_server_host}")
	private String robotSdkServerHost = "";

	@Value("${robot_sdk_server_port}")
	private int robotSdkServerPort;
	
	@PostConstruct
	public void init() {
		new Thread(() -> {

			EventLoopGroup bossGroup = new NioEventLoopGroup(1);
			EventLoopGroup workerGroup = new NioEventLoopGroup();
			try {
				ServerBootstrap b = new ServerBootstrap();
				b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
						.handler(new LoggingHandler(LogLevel.INFO)).childHandler(new RobotSdkServerInitializer());

				b.bind(robotSdkServerHost, robotSdkServerPort).sync().channel().closeFuture().sync();

			} catch (InterruptedException e) {
				logger.error(e.getMessage(),e);
			} finally {
				bossGroup.shutdownGracefully();
				workerGroup.shutdownGracefully();
			}

		}).start();
	}
	
	public static void fireSdkEvent(String eventString){
		channels.writeAndFlush(eventString+"\r\n");
	}
}
